package edu.lingnan.blog.user.controller;


import edu.lingnan.blog.api.model.LoginUser;
import edu.lingnan.blog.common.core.constant.UserConstants;
import edu.lingnan.blog.common.core.domain.R;
import edu.lingnan.blog.common.core.domain.pojo.User;
import edu.lingnan.blog.common.core.utils.StringUtils;
import edu.lingnan.blog.common.core.web.controller.BaseController;
import edu.lingnan.blog.common.core.web.domain.AjaxResult;
import edu.lingnan.blog.common.security.annotation.InnerAuth;
import edu.lingnan.blog.common.security.utils.SecurityUtils;
import edu.lingnan.blog.user.service.PermissionService;
import edu.lingnan.blog.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @author cql
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @InnerAuth
    @GetMapping("/info/{account}")
    public R<LoginUser> info(@PathVariable("account") String account) {
        User user = userService.selectUserByAccount(account);
        if (StringUtils.isNull(user)) {
            return R.fail("用户名或密码错误");
        }
        // TODO 实现这个
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user.getUserId());
        LoginUser userVo = new LoginUser();
        userVo.setUser(user);
        userVo.setRoles(roles);
        userVo.setPermissions(permissions);
        return R.ok(userVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@Validated @RequestBody User user) {
        String account = user.getAccount();
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(account))) {
            return R.fail("保存用户'" + account + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(user));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        Integer userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

}
